#!/usr/bin/env bash

#########################################################################
# Which Interpreter handle this script?
readonly INTERPRETER="$(readlink -fn "/proc/$$/exe")"

if [[ ! "bash" == "$(basename "${INTERPRETER}")" ]]; then
  echo "Interpreter \"${INTERPRETER}\" is not \"bash\"!"
  exit 1
fi

#########################################################################
# Script's location without symlink
readonly PWD0="$(dirname "$(readlink -fn "${BASH_SOURCE[0]}")")"

#########################################################################
function main() {
  readonly IMG_NAME="air/build-env"
  echo "===================================================="
  echo -n ">>>> Finding image builder ... "
  if command -v buildah; then
    declare -r CMD="buildah"
    declare -ra CMD_PARAMS=(
      bud
      --format docker
      --layers
      --pull=false
    )
  elif command -v docker; then
    declare -r CMD="docker"
    declare -ra CMD_PARAMS=(
      build
    )
  else
    echo "Neither podman nor docker existed!"
    exit 1
  fi
  echo "===================================================="
  declare img_tag
  img_tag="${IMG_NAME}:$(date +%Y%m%d_%H%M%S)"
  echo "Creating Image: ${img_tag}"
  set -e
  cd "${PWD0}"
  "${CMD}" "${CMD_PARAMS[@]}" \
    -f env.x86_64.dockerfile \
    -t "${img_tag}" .

  echo "===================================================="
  echo "Done."
  echo "===================================================="
}
main
